<template>
  <div class="relative h-screen" ref="videoContainer">
    <video
      ref="videoElement"
      id="videoElement"
      class="h-full w-full"
      playsinline
      preload="metadata"
    >
      <source :src="videoUrl" v-if="!videoUrl.startsWith('webrtc://')" />
    </video>
    <!-- 加载提示 -->
    <div
      v-if="isLoading"
      class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-70 text-white text-sm"
    >
      直播加载中...
    </div>
    <AutoPlay @close="play" type="直播" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch } from "vue";
import { usePlayerStore } from "@/store/usePlayer";
import AutoPlay from "@/components/AutoPlay.vue";
import { PlayerFactory } from "@/utils/playerFactory";

const playerStore = usePlayerStore();
const props = defineProps<{
  videoUrl: string;
  videoPoster: string;
  showTime: boolean;
}>();

const emit = defineEmits<{
  (e: "update", currentTime: number): void;
}>();

const videoElement = ref<HTMLVideoElement | null>(null);
const videoContainer = ref<HTMLElement | null>(null);
const isLoading = ref(false);
const player = ref<any>(null);

let lastTime = 0;
let watchedTime = 0;

const showLoading = () => {
  isLoading.value = true;
};

const hideLoading = () => {
  isLoading.value = false;
};

onMounted(() => {
  if (videoElement.value) {
    player.value = PlayerFactory.createPlayer({
      videoElement: videoElement.value,
      videoUrl: props.videoUrl,
      videoPoster: props.videoPoster,
      isPortrait: true,
      showTime: props.showTime,
      onTimeUpdate: time => {
        if (!isNaN(lastTime)) {
          let delta = time - lastTime;
          if (delta > 0 && delta < 1.0) {
            watchedTime += delta;
          }
        }
        lastTime = time;
        emit("update", watchedTime);
      },
      onLoadingChange: loading => {
        isLoading.value = loading;
      }
    });
  }
});

const play = () => {
  player.value?.play();
};

onUnmounted(() => {
  player.value?.destroy();
});
</script>

<style scoped lang="less">
:deep(.plyr__controls__item.plyr__control.plyr__control--pressed:first-child) {
  display: none;
}
:deep(.plyr) {
  height: 100%;
}
</style>
